﻿using System;
using System.IO;
using System.Threading;

namespace LuaVM.Core.Builtin
{
	class GlobalFuncs
	{
		LuaEnv m_lua = null;

		public GlobalFuncs(LuaEnv lua)
		{
			m_lua = lua;
			lua.RegisterFunction<GlobalFuncs>("Sleep", "sleep");
			lua.RegisterFunction<GlobalFuncs>(this, "Include", "include");
		}

		/// <summary>
		/// 在lua环境实现线程睡眠
		/// </summary>
		/// <param name="milliseconds">睡眠毫秒数</param>
		public static void Sleep(int milliseconds)
		{
			Thread.Sleep(milliseconds);
		}

		/// <summary>
		/// 在一个脚本中包含另一个脚本文件的内容，用来替换require函数，解决KopiLua不支持载入非ANSI编码lua脚本的问题
		/// </summary>
		/// <param name="name">要包含的脚本</param>
		/// <returns>脚本代码的第一个返回值</returns>
		public object Include(string name)
		{
			string path = GetFullPath(name);
			object[] objects = m_lua.DoFile(path);			
			if (objects == null || objects.Length == 0)
			{
				return null;
			}

			return objects[0];
		}

		private string GetFullPath(string name)
		{
			if (string.IsNullOrEmpty(name))
			{
				throw new ArgumentException("include: name is required.");
			}

			if (File.Exists(name))
			{
				return name;
			}

			string[] items = m_lua.GetPackagePath();
			foreach (string i in items)
			{
				string path = i.Replace("?", name);
				if (File.Exists(path))
				{
					return path;
				}
			}

			string message = "Cannot't match \"" + name + "\" with any of the package paths:\n";
			message += string.Join("\n", items);
			throw new FileNotFoundException(message);
		}
	}
}
